package com.fts.fts.fitness_tracking_system.utils;

import io.jsonwebtoken.*;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import java.security.Key;
import java.util.Date;

public class JwtUtil {
   // private static final Key SECRET_KEY;
    private static final String ISSUER = "your-issuer";
    private static final String AUDIENCE = "your-audience";


    // 密钥,用于签名和验证 JWT
    private static final Key SECRET_KEY = Keys.secretKeyFor(SignatureAlgorithm.HS256);

    // 生成 JWT
    public static String generateToken(String username, int userId) {
        return Jwts.builder()
                .setSubject(username) // 设置主题,通常是用户名
                .claim("userId", userId) // 自定义声明,存储用户 ID
                .setIssuer(ISSUER)
                .setAudience(AUDIENCE)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + 3600000))
                .signWith(SECRET_KEY, SignatureAlgorithm.HS256)
                .compact();
    }

    // 验证 JWT 并解析其中的信息
    public static Claims parseToken(String token) {
        try {
            return Jwts.parserBuilder()
                    .setSigningKey(SECRET_KEY)
                    .build()
                    .parseClaimsJws(token)
                    .getBody();
        } catch (ExpiredJwtException e) {
            throw e; // 明确传递过期异常
        } catch (JwtException e) {
            throw new JwtException("无效的Token: " + e.getMessage(), e);
        }
    }

    public static boolean validateToken(String token) {
        try {
            parseToken(token);
            return true;
        } catch (ExpiredJwtException ex) {
            System.out.println("Token 已过期");
            return false;
        } catch (JwtException ex) {
            System.out.println("无效的Token: " + ex.getMessage());
            return false;
        }
    }
}
